package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tbit.uqbike.client.constant.AccountConfigExtConstant;
import com.tbit.uqbike.client.dao.core.AccountConfigExtDao;
import com.tbit.uqbike.client.dao.core.AccountDao;
import com.tbit.uqbike.client.dao.core.AccountServiceConfigDao;
import com.tbit.uqbike.client.dao.core.BrandConfigDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.Account;
import com.tbit.uqbike.client.pojo.AccountServiceConfig;
import com.tbit.uqbike.client.pojo.dto.AccountCustomerServiceConfigDTO;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.service.AccountService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private AccountServiceConfigDao accountServiceConfigDao;
    @Autowired
    private AccountConfigExtDao accountConfigExtDao;
    @Autowired
    private BrandConfigDao brandConfigDao;

    @Override
    public void insert(Account account) {
        accountDao.insert(account);
    }

    @Override
    public Account getByTypeAndName(Integer type, String name) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("type", type);
        params.put("name", name);

        return accountDao.getByTypeAndName(params);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }


    @Override
    public Account getByAccountId(Integer accountId) {
        return accountDao.getByAccountId(accountId);
    }

    @Override
    public void authAccount(Integer brandAccountId, Integer accountId) {
        /**查询设备属于的代理商*/
        Account account = getByAccountId(accountId);
        if (account != null && !account.getParentId().equals(brandAccountId)) {
            throw new BaseException("-3015", "无权操作此车辆");
        }

    }

    @Override
    public List<Account> getByParentId(Integer parentId) {
        return accountDao.getByParentId(parentId);
    }

    @Override
    public Account getByAdAccountId(Integer accountId) {
        return accountDao.getByAdAccountId(accountId);
    }

    @Override
    public List<String> getByAccountIds(List<Integer> list) {
        return accountDao.getByAccountIds(list);
    }

    /**
     * @description: 获取当前时间段改平台、区域要展示的客服联系方式
     * @author: mo.shanyong
     * @date: 2024/11/26 19:52
     * @param: accountId 账户(区域、品牌)id
     * @return: com.tbit.uqbike.client.pojo.AccountServiceConfig
     */
    @Override
    public AccountCustomerServiceConfigDTO getServiceTel(Integer accountId) {
        AccountCustomerServiceConfigDTO serviceConfigDTO = new AccountCustomerServiceConfigDTO();
        Account account = accountDao.getByAccountId(accountId);
        serviceConfigDTO.setOfflineTip(account.getOfflineTip());

        AccountConfigExt accountConfigExt = accountConfigExtDao.
                selectByAccountIdAndKey(accountId, AccountConfigExtConstant.HUMAN_SERVICE_SWITCH_KEY);
        if (Objects.isNull(accountConfigExt) || StringUtils.isBlank(accountConfigExt.getParamValue())
                || !Objects.equals(accountConfigExt.getParamValue(),AccountConfigExtConstant.HUMAN_SERVICE_SWITCH_OPEN_VALUE)){
            return serviceConfigDTO;
        }

        //人工客服
        //到这里说明开启了开关
        //获取当前时间的小时和分钟组成的字符串
        String nowHourAndSecondStr = this.getNowHourAndSecondStr();
        AccountServiceConfig query = new AccountServiceConfig();
        query.setStartTime(nowHourAndSecondStr);
        query.setEndTime(nowHourAndSecondStr);
        query.setAccountId(accountId);
        List<AccountServiceConfig> serviceConfigList = accountServiceConfigDao.queryAllByLimit(query, null, null, null);
        if (CollectionUtils.isEmpty(serviceConfigList)){
            return serviceConfigDTO;
        }
        BeanUtils.copyProperties(serviceConfigList.get(0),serviceConfigDTO);
        splitRemarkAndTimeList(serviceConfigList, serviceConfigDTO);
        //只有一个电话号码匹配直接拷贝返回
        if (serviceConfigList.size() == 1){
            return serviceConfigDTO;
        }
        //有多个，则把电话号码合并，放到第一个中，然后返回第一个
        List<String> telPhoneList = serviceConfigList.stream().map(AccountServiceConfig::getTelephones).collect(Collectors.toList());
        serviceConfigDTO.setTelephones(String.join(",", telPhoneList));
        return serviceConfigDTO;
    }
    /**
     * 根据人工客服电话配置信息集合，按电话顺序拼接时间段集合和备注集合
     *
     * @param serviceConfigList List<AccountServiceConfig>
     */
    private void splitRemarkAndTimeList(List<AccountServiceConfig> serviceConfigList, AccountCustomerServiceConfigDTO serviceConfigDTO) {
        if (org.springframework.util.CollectionUtils.isEmpty(serviceConfigList)){
            return;
        }
        List<String> timeList = new ArrayList<>();
        List<String> remarkList = new ArrayList<>();
        for (AccountServiceConfig accountServiceConfig : serviceConfigList) {
            /**填充时间集合*/
            if (org.springframework.util.StringUtils.hasText(accountServiceConfig.getTelephones())){
                List<String> telephonesSplit = StrUtil.split(accountServiceConfig.getTelephones(), ",");
                for (String str : telephonesSplit) {
                    timeList.add(accountServiceConfig.getStartTime() + "-" + accountServiceConfig.getEndTime());
                }
            }
            /**填充备注集合*/
            if (!org.springframework.util.StringUtils.hasText(accountServiceConfig.getRemark())){
                List<String> remarkSplit = StrUtil.split(accountServiceConfig.getRemark(), "|||");
                for (String remark : remarkSplit) {
                    remarkList.add("");
                }
            } else{
                List<String> remarkSplit = StrUtil.split(accountServiceConfig.getRemark(), "|||");
                remarkList.addAll(remarkSplit);
            }
        }
        serviceConfigDTO.setTimeList(timeList);
        serviceConfigDTO.setRemarkList(remarkList);
    }

    /**
     * @description: 获取当前时间的小时和分钟组成的字符串
     * @author: mo.shanyong
     * @date: 2024/11/26 20:02
     * @return: java.lang.String
     */
    private String getNowHourAndSecondStr(){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        return dateFormat.format(date);
    }

    /**
     * @description: 获取在线客服信息
     * @author: mo.shanyong
     * @date: 2024/11/27 10:04
     * @param: accountId 账号id
     * @return: com.tbit.uqbike.client.pojo.dto.AccountCustomerServiceConfigDTO
     */
    @Override
    public AccountCustomerServiceConfigDTO getOnlineService(Integer accountId) {
        Account account = accountDao.getByAccountId(accountId);
        if (Objects.isNull(account)){
            return null;
        }
        AccountCustomerServiceConfigDTO serviceConfigDTO = new AccountCustomerServiceConfigDTO();
        //区域的在线客服开关、URL放在配置中
        List<AccountConfigExt> accountConfigExts = accountConfigExtDao.
                selectByAccountIdAndKeys(accountId, new HashSet<>(Arrays.
                        asList(AccountConfigExtConstant.ONLINE_SERVICE_SWITCH_KEY,AccountConfigExtConstant.ONLINE_SERVICE_URL_KEY)));
        if (CollectionUtils.isEmpty(accountConfigExts)){
            return null;
        }
        Map<String, String> keyValueMap = accountConfigExts.stream().collect(Collectors.toMap(AccountConfigExt::getParamKey, AccountConfigExt::getParamValue));
        String onlineServiceSwitch = keyValueMap.get(AccountConfigExtConstant.ONLINE_SERVICE_SWITCH_KEY);
        //在线客服
        if (StringUtils.isNotBlank(onlineServiceSwitch)){
            serviceConfigDTO.setOnlineServiceSwitch(Integer.valueOf(onlineServiceSwitch));
            serviceConfigDTO.setOnlineServiceUrl(keyValueMap.get(AccountConfigExtConstant.ONLINE_SERVICE_URL_KEY));
        }
        return serviceConfigDTO;
    }
}